package find;

/**
 * @author Liaorun
 */
public class KoKoEatingBananas {

    public static int minEatingSpeed(int[] piles, int h) {
        int L = 1;
        int R = 0;
        for (int pile : piles) {
            R = Math.max(R, pile);
        }

        int ans = 0;
        int M;

        while (L <= R) {
            M = L + ((R - L) >> 1);
            if (hours(piles, M) <= h) {
                ans = M;
                R = M - 1;
            } else {
                L = M + 1;
            }
        }

        return ans;
    }

    /**
     * 珂珂吃完香蕉需要的总时间 = 香蕉个数 / 吃香蕉的时间段 向上取整，在求和
     *
     * @param piles 每堆香蕉的个数
     * @param m
     * @return
     */
    private static int hours(int[] piles, int m) {
        int result = 0;

        for (int pile : piles) {
            result += (pile + m - 1) / m;
        }

        return result;
    }
}
